package com.example.eeuse.elasticsearch.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.file.FileReader;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.example.eeuse.elasticsearch.mapper.DocumentMapper;
import com.example.eeuse.elasticsearch.mapper.PlatformsMapper;
import com.example.eeuse.elasticsearch.model.Document;

import com.example.eeuse.elasticsearch.model.Platforms;
import com.example.eeuse.elasticsearch.service.JsonToEsService;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;
import org.apache.log4j.Logger;
import org.dromara.easyes.core.biz.EsPageInfo;
import org.dromara.easyes.core.biz.SAPageInfo;
import org.dromara.easyes.core.conditions.select.LambdaEsQueryWrapper;
import org.dromara.easyes.core.core.EsWrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import java.io.BufferedReader;
import java.util.ArrayList;
import java.util.List;




/**
 * 测试使用Easy-ES
 * <p>
 * Copyright © 2021 xpc1024 All Rights Reserved
 **/
@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ElasticTestController {
    private static final Logger logger = Logger.getLogger(ElasticTestController.class);
    private final DocumentMapper documentMapper;
    private final PlatformsMapper platformsMapper;
    private final JsonToEsService jsonToEsService;

    @GetMapping("/createIndex")
    public Boolean createIndex() {
        // 1.初始化-> 创建索引(相当于mysql中的表)
        return documentMapper.createIndex("documentx");
    }




    @GetMapping("/createIndexd")
    public Boolean createIndexd() {
        // 1.初始化-> 创建索引(相当于mysql中的表)
        return platformsMapper.createIndex("es_zyyt_platforms");
    }




    /**
     * 读取json文件批量写入easy-es
     *
     *
     * */


    @GetMapping("/importJsonToEsd")
    public String importJsonToEsd(@RequestParam("jsonFilePath") String jsonFilePath) {
//        String jsonFilePath = "/gpadmin/downloads/data.json";
//        String jsonFilePath = "/Users/www.macpe.cn/Downloads/data.json";
        jsonToEsService.readJSON(jsonFilePath);

        return "JSON data imported to Elasticsearch.";
    }




    @GetMapping("/insertd")
    public Integer insertd() {
        Document document = new Document();
        document.setTitle("老汉");
        document.setContent("技术过硬");
    return documentMapper.insert(document);

    }

    @GetMapping("/search")
    public List<Document> search() {
        // 3.查询出所有标题为老汉的文档列表
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.eq(Document::getTitle, "我的声明");
        return documentMapper.selectList(wrapper);
    }


    /**
     *
     *删除索引方法
     *
     *
     * */

    @GetMapping("/delete")
    public Boolean delete() {
        // 2.初始化->删除指定的索引
        return documentMapper.deleteIndex("document");
    }





    /**
     *
     * 根据指定的条件删除数据
     *
     *
     * */

    @GetMapping("/deleteData")
    public Integer deleteData() {
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        wrapper.eq(Document::getId,
                "a71g84kBH8vPiB23NWFA").or().eq(Document::getId,
                "kzvs9okBGgeVaaErx0Eu");
        return documentMapper.delete(wrapper);
    }








    /**
     *
     * 带分页的查询
     *
     *
     * */



    @GetMapping("/testSearchAfter")
    public void testSearchAfter() {
        LambdaEsQueryWrapper<Document> lambdaEsQueryWrapper = EsWrappers.lambdaQuery(Document.class);
        lambdaEsQueryWrapper.size(3);
        // 必须指定一种排序规则,且排序字段值必须唯一 此处我选择用id进行排序 实际可根据业务场景自由指定,不推荐用创建时间,因为可能会相同
        lambdaEsQueryWrapper.orderByDesc(Document::getId);
        SAPageInfo<Document> saPageInfo = documentMapper.searchAfterPage(lambdaEsQueryWrapper, null, 3);
        // 第一页
        System.out.println(saPageInfo);

        //assertEquals 报错为什么 这个版本太低了
//        Assertions.assertEquals(3, saPageInfo.getList().size());

        // 获取下一页
        List<Object> nextSearchAfter = saPageInfo.getNextSearchAfter();
        SAPageInfo<Document> next = documentMapper.searchAfterPage(lambdaEsQueryWrapper, nextSearchAfter, 3);

        System.out.println(next);

        //assertEquals 报错为什么  这个版本太低了
//        Assertions.assertEquals(3, next.getList().size());
    }






    /**pageQuery这个方法在传值的时候第一页是1，第二页从2开始，之后以此类推。这个是easy-es的bug，后面需要改正一下。
     *
     * */


    @GetMapping("/testPagination")
    public void testPaginationQuery() {
        try {
//            EsPageInfo<Document> result = documentMapper.pageQuery(EsWrappers.lambdaQuery(Document.class).eq(Document::getTitle, "个人简介"), 1, 3);
//            System.out.println("result = " + result);

            LambdaEsQueryWrapper<Document> queryWrapper = EsWrappers.lambdaQuery(Document.class)
                    .eq(Document::getTitle, "我的声明")
                    .and(wrapper -> wrapper
                            .like(Document::getContent, "河北")
                            .or()
                            .like(Document::getContent, "bin")
                    );



            logger.info(documentMapper.pageQuery(queryWrapper, 1, 3));

            EsPageInfo<Document> result = documentMapper.pageQuery(queryWrapper, 1, 3);
            System.out.println("result = " + result);






            if (result != null && result.getList() != null && !result.getList().isEmpty()) {
                ExcelWriter writer = ExcelUtil.getWriter("/Users/www.macpe.cn/Desktop/easy-es-springboot-demo/writeTest.xlsx");

                // 设置表头
                ArrayList<String> header = CollUtil.newArrayList("ID", "Title", "Content");
                writer.writeRow(header, true);

                // 遍历Document对象，获取属性值并写入Excel
                for (Document document : result.getList()) {
                    ArrayList<String> rowData = CollUtil.newArrayList(
                            document.getId(),
                            document.getTitle(),
                            document.getContent()
                    );
                    writer.writeRow(rowData, true);
                }

                writer.close();
                System.out.println("Excel file written successfully.");
            } else {
                System.out.println("No results found.");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }








    /**
    * 读取json文件批量写入easy-es
    *
    *
    * */


    @GetMapping("/importJsonToEs")
    public String importJsonToEs() {
        String jsonFilePath = "/Users/www.macpe.cn/Desktop/easy-es-springboot-demo/news.json";
        String indexName = "document";

        //jsonToEsService.importJsonToEs(jsonFilePath, indexName);

        return "JSON data imported to Elasticsearch.";
    }



    /**
     * 标准的sql查询 easy-es
     * 原生sql 分页会有问题，不能用原生的sql去写分页
     *
     * */


    @GetMapping("/testSQL")
    public void testSQL() {
        // 注意 sql中的from后面跟的是要被查询的索引名,也可以是索引别名(效果一样) 由于索引名可能会变,所以此处我采用别名ee_default_alias进行查询
//        String title="我的声明";
        String content="%bin%";
        String sql = "select content from document where content like'{}'";
        sql = StrUtil.format(sql, content);
        System.out.println("sql = " + sql);
        String jsonResult = documentMapper.executeSQL(sql);
        // 注意,执行后是以JSON格式返回,由用户按需自行解析
        System.out.println(jsonResult);
    }





    /**
    * 去重查询
    *
    * */



    @GetMapping("testSearch")

    public void testSearch(){
        // 测试只查询指定字段
        LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>();
        String content="bin";
        wrapper.match(Document::getContent, content);
        logger.info("查询的结果是:"+ documentMapper.pageQuery(wrapper, 1, 3));



        EsPageInfo<Document> result = documentMapper.pageQuery(wrapper, 1, 3);
        System.out.println("result = " + result);
    }

























}
